<?php
namespace App\Repositories;

use App\Exceptions\BasicException;
use App\Services\Tools\Export;
use App\Services\Tools\MapService;
use App\Services\Tools\HelperService;

class GiveGiftRepository
{
    //送礼记录导出
    public function export(array $params)
    {

        $gift_type = $params['gift_type'] ?? -1;
        if($gift_type != -1){
            //礼物分类条件，为了避免连表查询慢，单独处理
            return $this->getExportByGiftType($params);
        }

        $startTime = $params['start_time'] ?? '';
        $endTime = $params['end_time'] ?? '';
        $roomCode = $params['room_code'] ?? 0;
        $userCode = $params['user_code'] ?? 0;
        $mobile = $params['mobile'] ?? 0;

        $query = app('model_give_gift');
        if ($startTime && $endTime) {
            $query = $query->whereBetween('add_time', [strtotime($startTime), strtotime($endTime)]);
        } elseif ($startTime) {
            $query = $query->where('add_time', '>=', strtotime($startTime));
        } elseif ($endTime) {
            $query = $query->where('add_time', '<=', strtotime($endTime));
        }
        if ($roomCode) {
            $roomId = app('model_user_room')->where('room_id', $roomCode)->value('id');
            $query = $query->where('room_id', $roomId ?: 0);
        }
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $query = $query->where('user_id', $userId ?: 0);
        }
        if ($mobile) {
            $userId = app('model_user')->where('mobile', $mobile)->value('user_id');
            $query = $query->where('user_id', $userId ?: 0);
        }
        $count = $query->count();
        if ($count > 50000) {
            throw new BasicException(70202);
        }
        $list = $query->select('id','user_id','org_gift_id','number','room_id','add_time','org_total_price')
            ->orderBy('id', 'desc')
            ->get()->toArray();
        if (!empty($list)) {
            $userIds = array_unique(array_column($list, 'user_id'));
            $roomIds = array_column($list, 'room_id');
            $userMap = app('model_user')->whereIn('user_id', $userIds)->pluck('mobile', 'user_id');
            $userData = app('model_user_data')->select('user_id', 'user_code', 'nickname')->whereIn('user_id', $userIds)->get()->toArray();
            $userDataMap = array_column($userData, null, 'user_id');
            $giftDataMap = MapService::allGiftMap();
            $roomData = app('model_user_room')->whereIn('id', $roomIds)->select('id','room_id as room_code','room_name')->get()->toArray();
            $roomDataMap = array_column($roomData, null, 'id');
            $giftTypeMap = MapService::giftTypeMap();
            foreach ($list as &$value) {
                $giftType = $giftDataMap[$value['org_gift_id']]['type'] ?? '';
                $value['user_code'] = $userDataMap[$value['user_id']]['user_code'] ?? '';
                $value['nickname'] = HelperService::wxNickNameFormat($userDataMap[$value['user_id']]['nickname']) ?? '';
                $value['mobile'] = $userMap[$value['user_id']] ?? '';
                $value['gift_name'] = $giftDataMap[$value['org_gift_id']]['name'] ?? '';
                $value['gift_type'] = $giftTypeMap[$giftType]['name'] ?? '';
                $value['room_code'] = $roomDataMap[$value['room_id']]['room_code'] ?? '';
                $value['room_name'] = $roomDataMap[$value['room_id']]['room_name'] ?? '';
                $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
                $value['remark'] = '赠送 ' . $value['gift_name'] . ' X ' . $value['number'];
                if ($value['nickname'] && strpos($value['nickname'], '=') === 0) {
                    $value['nickname'] = "'" . $value['nickname'];
                }
            }
        }

        $fields = [
            ['field' => 'id', 'header' => '序号', 'width' => '18'],
            ['field' => 'user_code', 'header' => '用户编号', 'width' => '18'],
            ['field' => 'nickname', 'header' => '用户昵称', 'width' => '18'],
            ['field' => 'mobile', 'header' => '手机号', 'width' => '18'],
            ['field' => 'room_code', 'header' => '房间编号', 'width' => '18'],
            ['field' => 'room_name', 'header' => '房间名称', 'width' => '18'],
            ['field' => 'org_total_price', 'header' => '礼物价值', 'width' => '18'],
            ['field' => 'gift_type', 'header' => '礼物类别', 'width' => '18'],
            ['field' => 'remark', 'header' => '备注', 'width' => '18'],
            ['field' => 'add_time', 'header' => '时间', 'width' => '18']
        ];
        $downloadUrl = Export::exportUsePhpOffice('give_gift', $fields, $list);

        //记录日志
        app('model_admin_export_log')->add(31, $params, $downloadUrl);

        return ['download_url' => $downloadUrl];
    }

    //送礼记录列表
    public function list(array $params)
    {
        //礼物分类
        $gift_type = $params['gift_type'] ?? -1;
        if($gift_type != -1){
            //礼物分类条件，为了避免连表查询慢，单独处理
            return $this->getListByGiftType($params);
        }
        $startTime = $params['start_time'] ?? '';
        $endTime = $params['end_time'] ?? '';
        $roomCode = $params['room_code'] ?? 0;
        $userCode = $params['user_code'] ?? 0;
        $mobile = $params['mobile'] ?? 0;
        $page = $params['page'] ?? 1;
        $pageSize = $params['page_size'] ?? 20;
        $query = app('model_give_gift');
        if ($startTime && $endTime) {
            $query = $query->whereBetween('add_time', [strtotime($startTime), strtotime($endTime)]);
        } elseif ($startTime) {
            $query = $query->where('add_time', '>=', strtotime($startTime));
        } elseif ($endTime) {
            $query = $query->where('add_time', '<=', strtotime($endTime));
        }
        if ($roomCode) {
            $roomId = app('model_user_room')->where('room_id', $roomCode)->value('id');
            $query = $query->where('room_id', $roomId ?: 0);
        }
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $query = $query->where('user_id', $userId ?: 0);
        }
        if ($mobile) {
            $userId = app('model_user')->where('mobile', $mobile)->value('user_id');
            $query = $query->where('user_id', $userId ?: 0);
        }
        $totalQyery = $query;
        $totalPrice = $totalQyery->sum('total_price');
        $data = $query->orderBy('id', 'desc')
            ->paginate($pageSize ?: 20, ['*'], '', $page ?: 1)->toArray();
        if (!empty($data['data'])) {
            $userIds = array_unique(array_column($data['data'], 'user_id'));
            $roomIds = array_column($data['data'], 'room_id');
            $userMap = app('model_user')->whereIn('user_id', $userIds)->pluck('mobile', 'user_id');
            $userData = app('model_user_data')->select('user_id', 'user_code', 'nickname')->whereIn('user_id', $userIds)->get()->toArray();
            $userDataMap = array_column($userData, null, 'user_id');
            $giftDataMap = MapService::allGiftMap();
            $roomData = app('model_user_room')->whereIn('id', $roomIds)->select('id','room_id as room_code','room_name')->get()->toArray();
            $roomDataMap = array_column($roomData, null, 'id');
            $giftTypeMap = MapService::giftTypeMap();
            $giftUserIds = array_column($data['data'], 'gift_user');
            $giftUserData = app('model_user_data')->select('user_id', 'user_code', 'nickname')->whereIn('user_id', $giftUserIds)->get()->toArray();
            $giftUserDataMap = array_column($giftUserData, null, 'user_id');
            foreach ($data['data'] as &$value) {
                $giftType = $giftDataMap[$value['org_gift_id']]['type'] ?? '';
                $value['user_code'] = $userDataMap[$value['user_id']]['user_code'] ?? '';
                $value['nickname'] = $userDataMap[$value['user_id']]['nickname'] ?? '';
                $value['mobile'] = $userMap[$value['user_id']] ?? '';
                $value['gift_name'] = $giftDataMap[$value['org_gift_id']]['name'] ?? '';
                $value['gift_type'] = $giftTypeMap[$giftType]['name'] ?? '';
                $value['room_code'] = $roomDataMap[$value['room_id']]['room_code'] ?? '';
                $value['room_name'] = $roomDataMap[$value['room_id']]['room_name'] ?? '';
                $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
                $value['gift_user_code'] = $giftUserDataMap[$value['gift_user']]['user_code'] ?? '';
                $value['gift_nickname'] = $giftUserDataMap[$value['gift_user']]['nickname'] ?? '';
            }
        }
        return [
            'list' => $data['data'],
            'current_page' => $data['current_page'],
            'last_page' => $data['last_page'],
            'total' => $data['total'],
            'total_price' => $totalPrice
        ];
    }

    /**
     * 获取礼物今日总流水
     * @return bool
     */
    public function TotalGiveGift()
    {
        $where =  [strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59'))];
        $result = app('model_give_gift')->whereBetween('add_time',$where)->sum('total_price');;
        return $result;
    }


    //礼物类别下拉菜单
    public function getGiftType()
    {
        $list = app('model_gift_type')
            ->select('id','name')
            ->where('parent_id','>',0)
            ->get()->toArray();
        return $list;
    }
    //查询礼物分类列表
    public function getListByGiftType($params)
    {
        $startTime = $params['start_time'] ?? '';
        $endTime = $params['end_time'] ?? '';
        $roomCode = $params['room_code'] ?? 0;
        $userCode = $params['user_code'] ?? 0;
        $mobile = $params['mobile'] ?? 0;
        $page = $params['page'] ?? 1;
        $pageSize = $params['page_size'] ?? 20;
        $gift_type = $params['gift_type'] ?? -1;

        $query = app('model_give_gift')->from('ln_give_gift as gg');

        $query->leftJoin('ln_gift as g','g.id','=','gg.org_gift_id');
        if($gift_type != '-1'){
            $query = $query->where('g.type', $gift_type);
        }

        if ($startTime && $endTime) {
            $query = $query->whereBetween('gg.add_time', [strtotime($startTime), strtotime($endTime)]);
        } elseif ($startTime) {
            $query = $query->where('gg.add_time', '>=', strtotime($startTime));
        } elseif ($endTime) {
            $query = $query->where('gg.add_time', '<=', strtotime($endTime));
        }
        if ($roomCode) {
            $roomId = app('model_user_room')->where('room_id', $roomCode)->value('id');
            $query = $query->where('gg.room_id', $roomId ?: 0);
        }
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $query = $query->where('gg.user_id', $userId ?: 0);
        }
        if ($mobile) {
            $userId = app('model_user')->where('mobile', $mobile)->value('user_id');
            $query = $query->where('gg.user_id', $userId ?: 0);
        }
        $querySum = $query;
        // 统计金额
        $total_price = $querySum->sum('total_price');
        $data = $query->orderBy('gg.id', 'desc')
            ->paginate($pageSize ?: 20, ['gg.*','g.name as gift_name','g.type as gift_type'], '', $page ?: 1)->toArray();
        if (!empty($data['data'])) {
            $userIds = array_unique(array_column($data['data'], 'user_id'));
            $roomIds = array_column($data['data'], 'room_id');
            $userMap = app('model_user')->whereIn('user_id', $userIds)->pluck('mobile', 'user_id');
            $userData = app('model_user_data')->select('user_id', 'user_code', 'nickname')->whereIn('user_id', $userIds)->get()->toArray();
            $userDataMap = array_column($userData, null, 'user_id');
            $roomData = app('model_user_room')->whereIn('id', $roomIds)->select('id','room_id as room_code','room_name')->get()->toArray();
            $roomDataMap = array_column($roomData, null, 'id');
            $giftTypeMap = MapService::giftTypeMap();
            foreach ($data['data'] as &$value) {
                $value['user_code'] = $userDataMap[$value['user_id']]['user_code'] ?? '';
                $value['nickname'] = $userDataMap[$value['user_id']]['nickname'] ?? '';
                $value['mobile'] = $userMap[$value['user_id']] ?? '';
                $value['gift_name'] = $value['gift_name'] ?? '';
                $value['gift_type'] = $giftTypeMap[$value['gift_type']]['name'] ?? '';
                $value['room_code'] = $roomDataMap[$value['room_id']]['room_code'] ?? '';
                $value['room_name'] = $roomDataMap[$value['room_id']]['room_name'] ?? '';
                $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            }
        }

        return [
            'list' => $data['data'],
            'current_page' => $data['current_page'],
            'last_page' => $data['last_page'],
            'total' => $data['total'],
            'total_price' => $total_price
        ];
    }

    public function getExportByGiftType(array $params)
    {
        //礼物分类
        $gift_type = $params['gift_type'] ?? -1;

        $startTime = $params['start_time'] ?? '';
        $endTime = $params['end_time'] ?? '';
        $roomCode = $params['room_code'] ?? 0;
        $userCode = $params['user_code'] ?? 0;
        $mobile = $params['mobile'] ?? 0;

        $query = app('model_give_gift')->from('ln_give_gift as gg');

        $query->leftJoin('ln_gift as g','g.id','=','gg.org_gift_id');
        if($gift_type != '-1'){
            $query = $query->where('g.type', $gift_type);
        }

        if ($startTime && $endTime) {
            $query = $query->whereBetween('gg.add_time', [strtotime($startTime), strtotime($endTime)]);
        } elseif ($startTime) {
            $query = $query->where('gg.add_time', '>=', strtotime($startTime));
        } elseif ($endTime) {
            $query = $query->where('gg.add_time', '<=', strtotime($endTime));
        }
        if ($roomCode) {
            $roomId = app('model_user_room')->where('room_id', $roomCode)->value('id');
            $query = $query->where('gg.room_id', $roomId ?: 0);
        }
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $query = $query->where('gg.user_id', $userId ?: 0);
        }
        if ($mobile) {
            $userId = app('model_user')->where('mobile', $mobile)->value('user_id');
            $query = $query->where('gg.user_id', $userId ?: 0);
        }

        $count = $query->count();
        if ($count > 50000) {
            throw new BasicException(70202);
        }
        $list = $query->select('gg.id','gg.user_id','gg.org_gift_id','gg.number','gg.room_id','gg.add_time','gg.org_total_price','g.name as gift_name','g.type as gift_type')
            ->orderBy('id', 'desc')
            ->get()->toArray();
        if (!empty($list)) {
            $userIds = array_unique(array_column($list, 'user_id'));
            $roomIds = array_column($list, 'room_id');
            $userMap = app('model_user')->whereIn('user_id', $userIds)->pluck('mobile', 'user_id');
            $userData = app('model_user_data')->select('user_id', 'user_code', 'nickname')->whereIn('user_id', $userIds)->get()->toArray();
            $userDataMap = array_column($userData, null, 'user_id');
            $roomData = app('model_user_room')->whereIn('id', $roomIds)->select('id','room_id as room_code','room_name')->get()->toArray();
            $roomDataMap = array_column($roomData, null, 'id');
            $giftTypeMap = MapService::giftTypeMap();
            foreach ($list as &$value) {
                $value['user_code'] = $userDataMap[$value['user_id']]['user_code'] ?? '';
                $value['nickname'] = $userDataMap[$value['user_id']]['nickname'] ?? '';
                $value['mobile'] = $userMap[$value['user_id']] ?? '';
                $value['gift_name'] = $value['gift_name'] ?? '';
                $value['gift_type'] = $giftTypeMap[$value['gift_type']]['name'] ?? '';
                $value['room_code'] = $roomDataMap[$value['room_id']]['room_code'] ?? '';
                $value['room_name'] = $roomDataMap[$value['room_id']]['room_name'] ?? '';
                $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
                $value['remark'] = '赠送 ' . $value['gift_name'] . ' X ' . $value['number'];
            }
        }

        $fields = [
            ['field' => 'id', 'header' => '序号', 'width' => '18'],
            ['field' => 'user_code', 'header' => '用户编号', 'width' => '18'],
            ['field' => 'nickname', 'header' => '用户昵称', 'width' => '18'],
            ['field' => 'mobile', 'header' => '手机号', 'width' => '18'],
            ['field' => 'room_code', 'header' => '房间编号', 'width' => '18'],
            ['field' => 'room_name', 'header' => '房间名称', 'width' => '18'],
            ['field' => 'org_total_price', 'header' => '礼物价值', 'width' => '18'],
            ['field' => 'gift_type', 'header' => '礼物类别', 'width' => '18'],
            ['field' => 'remark', 'header' => '备注', 'width' => '18'],
            ['field' => 'add_time', 'header' => '时间', 'width' => '18']
        ];
        $downloadUrl = Export::exportUsePhpOffice('give_gift', $fields, $list);

        //记录日志
        app('model_admin_export_log')->add(31, $params, $downloadUrl);

        return ['download_url' => $downloadUrl];
    }
}
?>